import { useUserStore } from '@/stores/user'
import axios,{type Method} from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router'

// 创建axios实例，登录接口
const service = axios.create({
  baseURL: 'https://api-hmzs.itheima.net/tj',
  timeout: 5000,
})
//请求工具函数
export interface ServiceResponse<T>{
  code:number,
  data:T,
  msg:string
}
export const request =<T>(url:string, method:Method ='GET', submitData?:object)=>{
  // request 的三个范型参数说明：
  // request<默认data类型, 后端返回值类型, config 请求配置类型>
  return service.request<T,ServiceResponse<T>>({
    url:url,
    method:method,
    [method.toUpperCase() === 'GET' ? 'params' : 'data']: submitData
  })
}
//请求拦截器

service.interceptors.request.use(
  config => {
    const store =useUserStore()
    if(store.token){
     config.headers.Authorization = `Bearer ${store.token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  },
)
// 响应拦截器
service.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    if(error.respone){
      ElMessage.error(error.respone.data.msg)
      // 状态码判断，是否登录信息无效
      if (error.response.status === 401) {
        // 跳转到登录页
        router.push('/login')
        // 清除token信息
        const store = useUserStore()
        store.clearToken()
      }
  } else {
    // 后端无响应，网络异常(网络超时，无网络等错误)
    ElMessage.error('网络错误，请稍后重试')
  }
    return Promise.reject(error)
  },
)

export default service
